<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use think\facade\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    protected $relationSearch = true;

    protected $searchFields = 'id,user.username,worker.username,servicebasic.name,hospital.name';
    
    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $this->view->assign("medicineTypeList", $this->model->getmedicineTypeList());
        $this->view->assign("selfCareAbilityList", $this->model->getSelfCareAbilityList());
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->withJoin(['user','hospital','servicebasic','department','patient','worker'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->withJoin(['user','hospital','servicebasic','department','patient','worker'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                /*$row->visible(['id','user_id','patient_id','hospital_id','begin_time','create_time','finish_time','status','coupon_money','total_price','pay_price']);
                $row->getRelation('user')->visible(['username']);
				$row->getRelation('hospital')->visible(['name']);
				$row->getRelation('servicebasic')->visible(['name']);
				$row->getRelation('hospitaldepartment')->visible(['name']);*/

                $row->visible([
                    'id','user_id','patient_id','hospital_id','begin_time','create_time','finish_time','status','coupon_money','total_price','pay_price',
                    'user'=>['username'],
                    'worker'=>['username'],
                    'hospital'=>['name'],
                    'department'=>['name'],
                    'patient'=>['name'],
                    'servicebasic'=>['code','name'],
                ])->toArray();
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 回访订单
     */
    public function recall()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->withJoin(['user','hospital','servicebasic','department','patient','worker'])
                ->where($where)
                ->where('order.code','in',['severe_illness','oversea','private_doctor','famous_doctor'])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->withJoin(['user','hospital','servicebasic','department','patient','worker'])
                ->where($where)
                ->where('order.code','in',['severe_illness','oversea','private_doctor','famous_doctor'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible([
                    'id','user_id','patient_id','hospital_id','begin_time','create_time','finish_time','status','coupon_money','total_price','pay_price',
                    'user'=>['username'],
                    'worker'=>['username'],
                    'hospital'=>['name'],
                    'department'=>['name'],
                    'patient'=>['name'],
                    'servicebasic'=>['code','name'],
                ])->toArray();
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function transfer($id=null){
        if(!$id){
            $this->error('缺少订单id');
        }
        $order=$this->model::get(['id'=>$id]);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            Db::startTrans();
            try {
                if($params['worker_id']){
                    $transfer_arr=$order['transfer_arr']?json_decode($order['transfer_arr']):[];

                    if(!in_array($params['worker_id'],$transfer_arr)){
                        $transfer_arr[]=$params['worker_id'];
                        $order['transfer_arr']=json_encode($transfer_arr);
                    }

                    $order['status']=3;
                    $order['worker_id']=$params['worker_id'];
                    $order['transfer_time']=time();
                    $order->save();

                    //(new \app\common\model\User)->spare($params['worker_id'],0);
                    //(new \app\common\model\User)->spare($order['worker_id']);
                    \app\common\model\Notice::create([
                        'title'=>'派单提醒',
                        'content'=>'您有一个新的转单订单，请及时处理。',
                        'type'=>2,
                        'user_id'=>$params['worker_id'],
                        'order_id'=>$order['id']
                    ]);
                }
                else{
                    $order['status']=2;
                    $order['worker_id']=0;
                    $order['transfer_time']=time();
                    $order->save();
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
            Db::commit();
            $this->success('成功');
        }

        $this->view->assign("row", $order);
        return $this->view->fetch();
    }

    public function appoint($id=null){
        if(!$id){
            $this->error('缺少订单id');
        }
        $order=$this->model::get(['id'=>$id]);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            Db::startTrans();
            try {
                $transfer_arr=$order['transfer_arr']?json_decode($order['transfer_arr']):[];

                if(!in_array($params['worker_id'],$transfer_arr)){
                    $transfer_arr[]=$params['worker_id'];
                    $order['transfer_arr']=json_encode($transfer_arr);
                }

                $order['status']=3;
                $order['worker_id']=$params['worker_id'];
                $order['transfer_time']=time();
                $order->save();

                //(new \app\common\model\User)->spare($params['worker_id'],0);
                \app\common\model\Notice::create([
                    'title'=>'派单提醒',
                    'content'=>'您有一个新的订单，请及时处理。',
                    'type'=>2,
                    'user_id'=>$params['worker_id'],
                    'order_id'=>$order['id']
                ]);
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
            Db::commit();
            $this->success('成功');
        }

        $this->view->assign("row", $order);
        return $this->view->fetch();
    }

    public function newWorker(){
        $name=request()->param('name');
        $order_id=request()->param('order_id');

        $order=$this->model->with(['servicebasic','hospital'])
            ->where(['id'=>$order_id])
            ->find()->toArray()?:[];
        if(!$order)
            $this->error('未找到订单信息');

        $where=[
            'U.status'=>'normal',
            'U.working_status'=>1,
            'WF.city'=>$order['hospital']['city']
        ];

        if($order['servicebasic']['code']=='ward')
            $where['WF.phy_status']='normal';
        else
            $where['WF.pzy_status']='normal';



        [$noWhere, $sort, $order, $offset, $limit] = $this->buildparams();

        $U=new User();
        $total = $U->alias('U')
            ->leftjoin('worker_info WF','U.id=WF.user_id')
            ->where($where)
            ->whereLike('U.username',"%$name%")
            //->where('U.id','<>',$order['user_id'])
            ->where('WF.id_no','<>','')
            ->where('WF.id_card_front','<>','')
            ->where('WF.id_card_back','<>','')
            ->where('WF.hold_id_card','<>','')
            ->order('U.score desc')
            ->count();
        $list  = $U->alias('U')
            ->leftjoin('worker_info WF','U.id=WF.user_id')
            ->where($where)
            ->whereLike('U.username',"%$name%")
            //->where('U.id','<>',$order['user_id'])
            ->where('WF.id_no','<>','')
            ->where('WF.id_card_front','<>','')
            ->where('WF.id_card_back','<>','')
            ->where('WF.hold_id_card','<>','')
            ->order('U.score desc')
            ->field('U.*,WF.name')
            ->limit($offset, $limit)
            ->select();
        foreach ($list as $v) {
            $v->hidden(['password', 'salt']);
        }
        $result = ['total' => $total, 'rows' => $list];

        return json($result);
    }

    public function track(){
        $type=request()->param('type');
        $id=request()->param();

        if(!in_array($type,['start','finish']))
            $this->error('type参数错误');

        $order=$this->model->where(['id'=>$id])->find()?:[];
        if(!$order)
            $this->error('未找到订单信息');


        if($type=='start')
            $point=[[(float)$order['start_lon'],(float)$order['start_lat']]];
        if($type=='finish')
            $point=[[(float)$order['finish_lon'],(float)$order['finish_lat']]];

        $this->assign('point',$point);
        $this->assign('track',json_encode($point,JSON_OBJECT_AS_ARRAY));
        return $this->view->fetch();
    }
}
